/**
 * 
 */
package org.kalai.unifypay.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/** 
 * @Description: HTTP工具类
 * @author Renne66
 * @email 465119455@qq.com
 * @date 2016年8月5日 
*/
@SuppressWarnings("deprecation")
public class HttpUtil {
    private static final Logger logger = Logger.getLogger(HttpUtil.class);
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build(); 
	public static String sendGet(String url){
		String responseContent = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			if(httpEntity!=null){
				responseContent = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
		    logger.error("sendGet异常:"+e);
		}
		return responseContent;
	}
	
	public static String sendPost(String url, Map<String, Object> params){
		HttpPost httpPost = new HttpPost(url);// 创建httpPost 
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for(String key : params.keySet()) {
			nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
		    logger.error("sendPost异常:"+e);
		}
		return sendPost(httpPost);
	}
	
	public static String sendPost(String url, String params){
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setEntity(new StringEntity(params, "UTF-8"));
		return sendPost(httpPost);
	}
	
	private static String sendPost(HttpPost httpPost) {
		String responseContent = null;
		try {
			CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if(httpEntity!=null){
				responseContent = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
		    logger.error("sendPost异常:"+e);
		}
		return responseContent;
	}
	
	public static String sendHttpsPost(String url, Map<String, Object> params) {
		String responseContent = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for(String key : params.keySet()) {
				nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if(httpEntity!=null){
				responseContent = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
		    logger.error("sendHttpsPost异常:"+e);
		}
		return responseContent;
	}

	public static String sendHttpsPost(String url, String params){
		String responseContent = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new StringEntity(params, "UTF-8"));
			CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if(httpEntity!=null){
				responseContent = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
		    logger.error("sendHttpsPost异常:"+e);
		}
		return responseContent;
	}
	
	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {  
        SSLConnectionSocketFactory sslsf = null;  
        try {  
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {  
  
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
                    return true;  
                }  
            }).build();  
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {  
  
                @Override  
                public boolean verify(String arg0, SSLSession arg1) {  
                    return true;  
                }  
  
                @Override  
                public void verify(String host, SSLSocket ssl) throws IOException {  
                }  
  
                @Override  
                public void verify(String host, X509Certificate cert) throws SSLException {  
                }  
  
                @Override  
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {  
                }  
            });  
        } catch (GeneralSecurityException e) {  
            e.printStackTrace();  
        }  
        return sslsf;  
    }

}
